package com.example.huabei_competition.ui.fragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.example.huabei_competition.R;
import com.example.huabei_competition.callback.WelcomeCallback;
import com.example.huabei_competition.databinding.FragmentWelcomeBinding;
import com.example.huabei_competition.event.LiveDataManager;
import com.example.huabei_competition.event.UserUtil;
import com.example.huabei_competition.ui.activity.MainActivity;
import com.example.huabei_competition.util.MyApplication;
import com.example.huabei_competition.widget.CustomerDialog;
import com.example.huabei_competition.widget.WidgetUtil;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;

/**
 * Create by FanChenYang at 2021/2/24
 */
public class WelcomeFragment extends Fragment implements WelcomeCallback {


    private FragmentWelcomeBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        if (binding != null) {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent则从parent删除，防止发生这个rootview已经有parent的错误。
            ViewGroup mViewGroup = (ViewGroup) binding.getRoot().getParent();
            if (mViewGroup != null) {
                mViewGroup.removeView(binding.getRoot());
            }
            return binding.getRoot();
        }
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_welcome, container, false);
        binding.setCallback(this);

        initWeb();
        return binding.getRoot();
    }

    private int currentState;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LiveDataManager.getInstance().<Integer>with("webView").observe(getViewLifecycleOwner(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (currentState == 1) {
                    currentState = 0;
                    binding.web.loadUrl("http://39.105.171.41:8083/#/currentClass");
                }

                if (binding.web.canGoBack()) {
                    Log.d(TAG, "onChanged: goBackEnd");
                    binding.web.goBack();
                }
            }
        });
    }

    /**
     * 初始化web
     */
    private void initWeb() {
        WebSettings settings = binding.web.getSettings();
        settings.setJavaScriptEnabled(true);
        binding.web.loadUrl("http://39.105.171.41:8083/");
        binding.web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }

            @Override
            public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
                Log.d(TAG, "shouldOverrideKeyEvent: " + event.getAction());
                return super.shouldOverrideKeyEvent(view, event);
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Log.d(TAG, "shouldInterceptRequest: " + request.getUrl());
                if (request.getUrl().toString().equals("http://39.105.171.41:8083/")) {
                    currentState = 1;
                    Log.d(TAG, "shouldInterceptRequest: YYYYYYYYYYYY");
                }
                return super.shouldInterceptRequest(view, request);
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.web.onResume();
        currentState = 1;
    }

    @Override
    public void onStop() {
        super.onStop();
        binding.web.onPause();
    }

    private static final String TAG = "WelcomeFragment";

    @Override
    public void onShopClick() {
        ((MainActivity) getActivity()).getController().navigate(R.id.action_mainFragment_to_shopFragment);
    }

    @Override
    public void onDataShowClick() {
        LiveDataManager.getInstance().<String>with(DataShowFragment.class.getSimpleName()).setValue(UserUtil.sUserName);
        ((MainActivity) getActivity()).getController().navigate(R.id.action_mainFragment_to_dataShowFragment);
    }

    @Override
    public void onSayingClick() {
        CustomerDialog customerDialog = new CustomerDialog();
        customerDialog.setLayoutId(R.layout.fragment_famous_quotes);
        customerDialog.setCancelable(false);
        customerDialog.setmHeight(1200);
        customerDialog.setCallback(view -> {
            view.findViewById(R.id.btn_close).setOnClickListener(v -> {
                customerDialog.dismiss();
            });
            TextView content = view.findViewById(R.id.tv_quote);
            content.setText(((MyApplication) getActivity().getApplication()).loadOneQuote());
            WidgetUtil.setCustomerText(content, WidgetUtil.CUSTOMER_HUAKANGSHAONV);
        });
        customerDialog.show(getActivity().getSupportFragmentManager(), "quote");
    }
}